package com.zfast.spring5.config;


import com.zfast.spring5.MD5Util;
import com.zfast.spring5.repository.UserRepository;
import com.zfast.spring5.service.CustomUserDetailsService;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @author zgn
 * @Description: SecurityConfig
 * @date 2022/3/3 0003
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    CustomUserDetailsService userDetailsService;

    @Bean
    public  PasswordEncoder encoder(){
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return MD5Util.encode((String)rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(MD5Util.encode((String)rawPassword));
            }
        };
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //region 1.基于内存的用户存储
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("{noop}123123").authorities("admin")
                .and().withUser("test").password("{noop}123123").authorities("admin")
        ;*/
        //endregion

        //region 2.自定义用户认证
        auth.userDetailsService(userDetailsService)
                //.passwordEncoder(encoder())
        ;
        //endregion
    }

    //会和默认的配置冲突
    /*@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/home").hasRole("admin")
                .antMatchers("/","/**").permitAll()
                //.and().formLogin().loginPage("/login")
        ;

    }*/
}
